/*!
 * vinculum
 * Copyright(c) 2017 azzly
 * MIT Licensed
 */
 
'use strict';

/**
 * Module dependencies.
 * @private
 */

const helper = require('./helper');
const debug = require('./debug')(__filename);
const cache = require('./cache');
const ejs = require('ejs');
const fs = require('fs');

const templatesPath = `${__dirname}/templates/`;
const templateExt = ".ejs";

class template {
  static render(template_name = 'index',data = {},option = {}){
    return new Promise((resolve, reject)=>{
      resolve(template.findFn(template_name,option)(data));
    });
  }
	
	static renderStr(template_str,data = {},option = {}){
    return new Promise((resolve, reject)=>{
      resolve(template.findStrFn(template_str,option)(data));
    });
  }
  
  static findFn(template_name,option){
    let cache_name = helper.md5(template_name + helper.stringify(option));
    let template_fn = cache.getRenderFileFn(cache_name);
    if(!template_fn){
      let str = template.findStr(template_name);
      template_fn = ejs.compile(str,option);
      cache.setRenderFileFn(cache_name,template_fn);
    }
    return template_fn;
  }  
	
	static findStrFn(template_str,option){
    let cache_name = helper.md5(template_str + helper.stringify(option));
    let template_fn = cache.getRenderFileFn(cache_name);
    if(!template_fn){
      template_fn = ejs.compile(template_str,option);
      cache.setRenderFileFn(cache_name,template_fn);
    }
    return template_fn;
  }
  
  static findStr(file_name){
    let template_str = cache.getRenderFile(file_name);
    if(!template_str){
      template_str = fs.readFileSync(templatesPath + file_name + templateExt,'utf8');
      cache.setRenderFile(file_name,template_str);
    }
    return template_str;
  }
}

module.exports = template;